#!/usr/bin/env python3

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import glob
import json
import shutil
import subprocess
from datetime import datetime
from iptvwh import GameId, Source
from iptvwh import EwProvider, ProviderNotSynchronized, BadProviderContent, SourceNotInProvider


class ProviderImpl(EwProvider):

    @property
    def name(self):
        return "linuxgame"

    @property
    def last_sync_datetime(self):
        return datetime.min

    def sync(self, common):
        Util.gitPull("https://github.com/rwv/chinese-dos-games", common.cache_dir)

    def list_games(self, common):
        if not self._isGamesJsonExist(common.cache_dir):
            raise ProviderNotSynchronized(self.name)

        ret = []
        for k, v in self._parseGamesJson(common.cache_dir).items():
            if k != v["identifier"]:
                raise BadProviderContent(self.name, "Bad data for game \"%s\" in data source \"%s\"" % (k, self.name))
            ret.append(GameId("dos", k))
        return ret

    def get_game_info(self, common, game_platform, game_name):
        ret = self._parseGamesJson(common.cache_dir).get(game_platform, game_name)
        if ret is None:
            raise SourceNotInProvider(self.name, game_platform, game_name)
        else:
            return Source(
                default_language="zh_CN",
                names=self._toNames(ret),
                release_year=ret.get("releaseYear"),
                files={
                    Source.StdFileType.COVER
                }
            )

        # "executable": "PM2.COM",
        # "links": {
        #     "Princess Maker 2 - Wikipedia": "https://en.wikipedia.org/wiki/Princess_Maker_2"
        # },
        # "coverFilename": "cover.jpg",

    def get_game_file_urls(self, common, game_id):
        return

    def get_auxillary_file_urls(self, common, game_id, file_name):
        return

    def _isGamesJsonExist(self, cacheDir):
        fullfn = os.path.join(cacheDir, "game.json")
        return os.path.exists(fullfn)

    def _parseGamesJson(self, cacheDir):
        jsonData = None
        with open(os.path.join(cacheDir, "game.json"), "r") as f:
            jsonData = json.load(f)["games"]
        return jsonData

    def _toNames(self, oneGameData):
        ret = {}
        if "zh-Hans" in oneGameData:
            ret["zh_CN"] = oneGameData["zh-Hans"]
        if "zh-Hant" in oneGameData:
            ret["zh_TW"] = oneGameData["zh-Hant"]
        if "en" in oneGameData:
            ret["en_US"] = oneGameData["en"]
        return ret

    def _toFiles(self, oneGameData):
        ret = {}
        if "coverFilename" in oneGameData:
            ret[Source.StdFileType.COVER] = oneGameData["coverFilename"]
        return ret






import subprocess
import hashlib
import inspect
import os
import json
import urllib.request

from concurrent.futures import ThreadPoolExecutor, wait

root = os.path.dirname(os.path.abspath(
    inspect.getfile(inspect.currentframe())))

PREFIX = "https://dos-bin.zczc.cz/"
DESTINATION = os.path.join(root, 'bin')
BUF_SIZE = 65536
THREAD_SIZE = 10

# read game infos from games.json
with open(os.path.join(root, 'games.json'), encoding='utf8') as f:
    game_infos = json.load(f)


def generate_sha256(file):
    sha256 = hashlib.sha256()
    with open(file, 'rb') as f:
        while True:
            data = f.read(BUF_SIZE)
            if not data:
                break
            sha256.update(data)
    return sha256.hexdigest()


def update(identifier, url, file):
    print(f'Downloading {identifier} game file')
    urllib.request.urlretrieve(url, file)


def main(prefix=PREFIX, destination=DESTINATION):
    # create folder
    os.makedirs(destination, exist_ok=True)

    executor = ThreadPoolExecutor(max_workers=THREAD_SIZE)
    all_task = list()

    downloaded = list()
    for identifier in game_infos['games'].keys():
        file = os.path.normcase(os.path.join(destination, identifier + '.zip'))
        url = prefix + urllib.parse.quote(identifier) + '.zip'
        if os.path.isfile(file) and generate_sha256(file) == game_infos['games'][identifier]['sha256']:
            print(f'skip {identifier}')
        else:
            subprocess.run(["wget", "-c", "-O", file, url])


if __name__ == '__main__':
    main()
